from flask import request, jsonify, current_app
from flask_jwt_extended import jwt_required
from ..models import SystemLog
from .. import db
from ..utils import success_response, error_response
from . import api

@api.route('/logs', methods=['GET'])
@jwt_required()
def get_logs():
    """获取系统日志列表"""
    try:
        page = int(request.args.get('page', 1))
        per_page = int(request.args.get('limit', 10))
        level = request.args.get('level', '')
        keyword = request.args.get('keyword', '')
        
        # 构建查询
        query = SystemLog.query
        
        # 根据日志级别筛选
        if level:
            query = query.filter(SystemLog.level == level)
        
        # 根据关键字筛选
        if keyword:
            query = query.filter(
                SystemLog.message.contains(keyword) |
                SystemLog.module.contains(keyword) |
                SystemLog.user.contains(keyword)
            )
        
        # 按时间倒序排列
        query = query.order_by(SystemLog.timestamp.desc())
        
        # 分页
        pagination = query.paginate(page=page, per_page=per_page, error_out=False)
        
        logs = [{
            'id': log.id,
            'level': log.level,
            'module': log.module,
            'message': log.message,
            'user': log.user,
            'timestamp': log.timestamp.isoformat() if log.timestamp else None
        } for log in pagination.items]
        
        result = {
            'items': logs,
            'total': pagination.total,
            'pages': pagination.pages,
            'current_page': page
        }
        
        return success_response(result, '获取成功')
    except Exception as e:
        current_app.logger.error(f'获取系统日志列表错误: {str(e)}')
        return error_response('获取系统日志列表失败', 500)

@api.route('/logs/<int:log_id>', methods=['DELETE'])
@jwt_required()
def delete_log(log_id):
    """删除系统日志"""
    try:
        log = SystemLog.query.get(log_id)
        if not log:
            return error_response('日志不存在', 404)
        
        db.session.delete(log)
        db.session.commit()
        
        return success_response(None, '删除成功')
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'删除系统日志错误: {str(e)}')
        return error_response('删除系统日志失败', 500)

@api.route('/logs/clear', methods=['DELETE'])
@jwt_required()
def clear_logs():
    """清空系统日志"""
    try:
        SystemLog.query.delete()
        db.session.commit()
        
        return success_response(None, '清空成功')
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'清空系统日志错误: {str(e)}')
        return error_response('清空系统日志失败', 500)